package cn.com.cloudpioneer.evaluate.service;

import cn.com.cloudpioneer.evaluate.mapper.ItemMapper;
import cn.com.cloudpioneer.evaluate.mapper.TargetMapper;
import cn.com.cloudpioneer.evaluate.mapper.TaskMapper;
import cn.com.cloudpioneer.evaluate.model.ItemModel;
import cn.com.cloudpioneer.evaluate.model.ResourceModel;
import cn.com.cloudpioneer.evaluate.model.TargetModel;
import cn.com.cloudpioneer.evaluate.model.TaskModel;
import cn.com.cloudpioneer.evaluate.utils.CustomException;
import cn.com.cloudpioneer.evaluate.utils.StringUtil;
import cn.com.cloudpioneer.evaluate.utils.SuffixUtils;
import cn.com.cloudpioneer.evaluate.utils.ZNUtils;
import com.google.common.collect.Lists;
import org.apache.commons.net.ftp.*;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.zip.InflaterInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @auther maruikai
 * @create 2023/9/14-17:14
 */
@Service
public class FileService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);

    @Value("${ftp.client.hostname}")
    private String hostname;
    @Value("${ftp.client.port}")
    private int port;
    @Value("${ftp.client.username}")
    private String username;
    @Value("${ftp.client.password}")
    private String password;
    @Value("${ftp.client.baseDataPath}")
    private String baseDataPath;
    @Value("${ftp.client.baseTargetFilePath}")
    private String baseTargetFilePath;
    @Value("${ftp.client.baseDocPackagePath}")
    private String baseDocPackagePath;
    @Value("${ftp.client.baseDocReportPath}")
    private String baseDocReportPath;
    @Value("${ftp.client.baseResultPath}")
    private String baseResultPath;
    @Value("${file.kkview.basepath}")
    private String kkFileViewPrefix;

    @Resource
    private TaskMapper taskMapper;
    @Resource
    private ItemMapper itemMapper;
    @Resource
    private TargetMapper targetMapper;

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ItemService itemService;

    public FTPClient ClientFtp() {
        //连接FTP服务器
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(hostname, port);
            //设置文件编码
            ftp.setControlEncoding("GBK");
            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
            conf.setServerLanguageCode("zh");
            ftp.login(username, password);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                LOGGER.info("ftp服务未启动{}", ftp.getReplyCode());
                ftp.disconnect();
                return null;
            }
            ftp.setConnectTimeout(100000);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        LOGGER.info("ftp服务已启动 :{}", ftp.getReplyString());
        return ftp;
    }

    public void uploadTargetFile(String targetId, MultipartFile file) throws CustomException {
        String filename = this.getFileName(file.getOriginalFilename());
        try {
            TargetModel targetModel = targetMapper.findByTargetId(targetId);
            if (targetModel == null) throw new CustomException(5005, "无法找到此项目!");
            if (!targetModel.getFileRules().equals(filename))
                throw new CustomException(5007, "文件名与文件规则不一致");
            String path = this.getPath(targetId, 3);
            String pinyin = ZNUtils.toPinyin(Objects.requireNonNull(filename));
            this.uploadFile(path, pinyin, file.getInputStream());
            targetMapper.setFilePath(targetId, path + "/" + pinyin);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getFileName(String filename) throws CustomException {
        if (StringUtil.isEmpty(filename)) throw new CustomException(5007, "文件名错误!");
        if (filename.substring(filename.lastIndexOf(".") + 1).equals("docx"))
            throw new CustomException(5007, "文件类型错误，请上车.docx文件!");
        return filename;
    }

    public void uploadDocumentData(String taskId, MultipartFile file) throws CustomException {
        String filename = this.getFileName(file.getOriginalFilename());
        try {
            String path = this.getPath(taskId, 4);
            String pinyin = ZNUtils.toPinyin(Objects.requireNonNull(filename));
            this.uploadFile(path, pinyin, file.getInputStream());
            taskMapper.setFilePath(taskId, path + "/" + pinyin);
            List<ResourceModel> byObjIdAndPath = resourceService.findByObjIdAndPath(taskId, path + "/" + pinyin);
            if (byObjIdAndPath.size() == 0) {
                ResourceModel resourceModel = new ResourceModel(taskId, filename, path + "/" + pinyin, 2);
                resourceService.addResource(resourceModel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void uploadReportFile(String itemId, MultipartFile file) throws CustomException {
        String filename = this.getFileName(file.getOriginalFilename());
        try {
            String path = this.getPath(itemId, 5);
            String pinyin = ZNUtils.toPinyin(Objects.requireNonNull(filename));
            this.uploadFile(path, pinyin, file.getInputStream());
            List<ResourceModel> byObjIdAndPath = resourceService.findByObjIdAndPath(itemId, path + "/" + pinyin);
            if (byObjIdAndPath.size() == 0) {
                ResourceModel resourceModel = new ResourceModel(itemId, filename, path + "/" + pinyin, 1);
                resourceService.addResource(resourceModel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //评估文件解压
    public void uploadEvaluateFile(String itemId, MultipartFile file) throws CustomException {
        if (!Objects.requireNonNull(file.getOriginalFilename()).endsWith(".zip")) {
            throw new CustomException(5006, "文件格式错误！请上传.zip格式文件");
        }
        ItemModel byId = itemMapper.findById(itemId);
        if (byId == null) throw new CustomException(5005, "无法找到此项目!");
        try {
            if (!StringUtil.isEmpty(byId.getFilePath())) {
                this.delFile(byId.getFilePath(), 2);
            }
            String path = this.getPath(itemId, 1);
            this.uploadFile(path, file.getOriginalFilename(), file.getInputStream());
            itemMapper.updateStatusAndPath(path + "/" + file.getOriginalFilename(), 1, itemId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void distributeFile(String itemId) throws CustomException {
        ItemModel item = itemMapper.findById(itemId);
        if (item == null) throw new CustomException(5005, "无法找到此项目!");

        try {
            String filePath = item.getFilePath();
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            String basePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);

            FTPClient ftpClient = this.ClientFtp();
            boolean directory = ftpClient.changeWorkingDirectory(new String(basePath.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
            if (!directory) {
                itemMapper.updateStatus(2, itemId);
                throw new CustomException(5005, "文件无法打开!");
            }
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile ftpFile : ftpFiles) {
                if (ftpFile.getName().equals(fileName)) {
                    // 设置以二进制流的方式传输
                    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    InputStream inputStream = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
                    //获取文件输入流，压缩文件直接读取
                    InputStream in = new BufferedInputStream(inputStream);
                    ZipInputStream zipIn = new ZipInputStream(in, Charset.forName("gbk"));
                    ZipEntry zipEntry;
                    while ((zipEntry = zipIn.getNextEntry()) != null) {
                        if (zipEntry.isDirectory()) {
                            continue;
                        }
                        if (zipEntry.toString().endsWith("doc") || zipEntry.toString().endsWith("docx")) {
                            List<TaskModel> byItemIn = taskMapper.findChildByItemId(itemId);
                            if (byItemIn.size() == 0) {
                                itemMapper.updateStatus(3, itemId);
                                return;
                            }
                            String file_name = zipEntry.getName().substring(zipEntry.getName().lastIndexOf("/") + 1);
                            for (TaskModel taskModel : byItemIn) {
                                List<TargetModel> byTaskId = targetMapper.findByTaskId(taskModel.getTaskId());
                                for (TargetModel targetModel : byTaskId) {
                                    if (targetModel.getUploadFlag() && targetModel.getFileRules().contains(file_name)) {
                                        byte[] aByte = getByte(zipIn);
                                        InputStream byteArrayInputStream = new ByteArrayInputStream(aByte);
                                        String path_url = this.getPath(targetModel.getTargetId(), 3);
                                        String pinyin = ZNUtils.toPinyin(file_name);
                                        uploadFile(path_url, pinyin, byteArrayInputStream);
                                        targetMapper.setFilePath(targetModel.getTargetId(), path_url + "/" + pinyin);
                                    }
                                }
                            }
                        }
                    }
                    zipIn.close();
                    in.close();
                    inputStream.close();
                }
            }
            itemMapper.updateStatus(3, itemId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void uploadFile(String path, String fileName, InputStream inputStream) {
        try {
            FTPClient ftpClient = this.ClientFtp();
            //让客户端告诉服务端开通一个端口用来数据传输（必须要 不然会一直卡死）
            ftpClient.enterLocalPassiveMode();
            //循环生成目录并进入
            stringPath(ftpClient, path);
            //如果缺省该句 传输txt正常 但图片和其他格式的文件传输出现乱码
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //开始上传
            ftpClient.storeFile(new String(fileName.getBytes("GBK"), StandardCharsets.ISO_8859_1), inputStream);
            //关闭输入流
            inputStream.close();
            this.ftpLogout(ftpClient);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    public boolean delFile(String intactPath, int type) throws CustomException {

//        String path = new String(Base64.decodeBase64(intactPath.getBytes()));
        try {
            FTPClient ftpClient = this.ClientFtp();
            String fileName = intactPath.substring(intactPath.lastIndexOf("/") + 1);
            String basePath = intactPath.substring(0, intactPath.lastIndexOf("/") + 1);

            boolean directory = ftpClient.changeWorkingDirectory(new String(basePath.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
            if (!directory) {
                throw new CustomException(5005, "文件无法打开!");
            }
            boolean b = ftpClient.deleteFile(new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
            this.ftpLogout(ftpClient);
            if (b) {
                this.clearFilePath(intactPath, type);
            }
            return b;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(5010, "删除文件失败");
        }
    }

    public String downloadFile(String intactPath, Long id) throws CustomException {
        String realName;
        String fileName;
        String basePath;
        if (!StringUtil.isEmpty(id)) {
            ResourceModel serviceById = resourceService.findById(id);
            if (serviceById == null) {
                throw new CustomException(5006, "无法找到此资源!");
            }
            fileName = serviceById.getFilePath().substring(serviceById.getFilePath().lastIndexOf("/") + 1);
            basePath = serviceById.getFilePath().substring(0, serviceById.getFilePath().lastIndexOf("/") + 1);
            realName = serviceById.getFileName();
        } else {
            if (StringUtil.isEmpty(intactPath)) {
                throw new CustomException(5007, "文件路径不能为空!");
            }
            fileName = intactPath.substring(intactPath.lastIndexOf("/") + 1);
            basePath = intactPath.substring(0, intactPath.lastIndexOf("/") + 1);
            String objId = this.getObjId(basePath, 1);
            TargetModel byTargetId = targetMapper.findByTargetId(objId);
            if (byTargetId == null) {
                throw new CustomException(5006, "无法找到此指标!");
            }
            realName = byTargetId.getFileRules();
        }
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String encode = base64Encoder.encode(basePath.getBytes());
        String downUrl = String.format("http://118.118.118.247:38090/api/xgs/file/download_file?basePath=%s&fileName=%s&realName=%s", encode, fileName, realName);
        return downUrl.replaceAll("\r", "").replaceAll("\n", "");
    }

    public void download(String basePath, String fileName, String downloadFileName, HttpServletResponse response) throws CustomException {

        FTPClient ftpClient = this.ClientFtp();
        try {
            ftpClient.enterLocalActiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            byte[] decode = Base64.getDecoder().decode(basePath.getBytes(StandardCharsets.UTF_8));
            String filePath = new String(decode, StandardCharsets.UTF_8);

            boolean directory = ftpClient.changeWorkingDirectory(new String(filePath.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
            if (!directory) {
                throw new CustomException(5005, "文件无法打开!");
            }
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile ftpFile : ftpFiles) {
                if (ftpFile.getName().equals(fileName)) {

                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/x-download");
                    //解决中文不能生成文件（包含空格）
                    String realName = URLEncoder.encode(downloadFileName, "UTF-8");
                    response.setHeader("Content-Disposition", "attachment; filename=\""
                            + realName.replaceAll("\\+", "%20") + "\"");
                    //传输模式
                    ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
                    // 设置以二进制流的方式传输
                    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    InputStream inputStream = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
                    OutputStream outputStream = response.getOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buffer, 0, 1024)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                    break;
                }
            }
            this.ftpLogout(ftpClient);
        } catch (Exception e) {
            throw new CustomException(5010, "下载失败");
        }
    }

    public Object getFileList(String taskId) throws CustomException {
        return taskService.getDocumentList(taskId);
    }

    public Object getReportFileList(String itemId) throws CustomException {
        return itemService.getReportFileList(itemId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delResource(long id) throws CustomException {
        ResourceModel resource = resourceService.findById(id);
        if (resource == null) throw new CustomException(5004, "无法找到此资源!");

        boolean delFlag = this.delFile(resource.getFilePath(), 4);
        if (delFlag) {
            resourceService.delFile(id);
        }
    }

    private void stringPath(FTPClient ftpClient, String path) throws IOException {
        //循环路径 没有目录则创建目录
        List<String> string = Lists.newArrayList();
        string.addAll(Arrays.asList((path).split("/")));
        StringBuilder paths = new StringBuilder();
        for (String s : string) {
            paths.append("/").append(new String(s.getBytes("GBK"), StandardCharsets.ISO_8859_1));
            if (!ftpClient.changeWorkingDirectory(paths.toString())) {
                ftpClient.makeDirectory(paths.toString());
            }
        }
        ftpClient.changeWorkingDirectory(paths.toString());
    }

    /**
     * 获取条目byte[]字节
     */
    public byte[] getByte(InflaterInputStream zis) {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            int length;
            while ((length = zis.read(temp, 0, 1024)) != -1) {
                bout.write(temp, 0, length);
            }
            byte[] buf = bout.toByteArray();
            bout.close();
            return buf;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private String getPath(String objId, Integer type) throws CustomException {
        ItemModel item;
        TaskModel task;
        TargetModel target;
        String path_url = "";
        switch (type) {
            case 1:
                item = itemMapper.findById(objId);
                if (item == null) throw new CustomException(5005, "无法找到此项目!");
                path_url = baseDocPackagePath.replace("{projectname}", item.getItemId());
                break;
            case 2:
                task = taskMapper.findById(objId);
                if (task == null) throw new CustomException(5004, "无法找到此任务!");
                item = itemMapper.findById(task.getItemId());
                if (item == null) throw new CustomException(5005, "无法找到此项目!");
                path_url = baseResultPath.replace("{projectname}", item.getItemId()).
                        replace("{enName}", task.getTaskId());
                break;
            case 3:
                target = targetMapper.findByTargetId(objId);
                if (target == null) throw new CustomException(5006, "无法找到此指标!");
                task = taskMapper.findById(target.getTaskId());
                if (task == null) throw new CustomException(5004, "无法找到此任务!");
                item = itemMapper.findById(task.getItemId());
                if (item == null) throw new CustomException(5005, "无法找到此项目!");
                path_url = baseTargetFilePath.replace("{targetName}", target.getTargetId())
                        .replace("{projectname}", item.getItemId()).
                                replace("{enName}", task.getTaskId());
                break;
            case 4:
                task = taskMapper.findById(objId);
                if (task == null) throw new CustomException(5004, "无法找到此任务!");
                item = itemMapper.findById(task.getItemId());
                if (item == null) throw new CustomException(5005, "无法找到此项目!");
                path_url = baseDataPath.replace("{projectname}", item.getItemId()).
                        replace("{enName}", task.getTaskId());
                break;
            case 5:
                item = itemMapper.findById(objId);
                if (item == null) throw new CustomException(5005, "无法找到此项目!");
                path_url = baseDocReportPath.replace("{projectname}", item.getItemId());
                break;

        }
        return path_url;
    }

    public void clearFilePath(String path, Integer type) {
        String objId = this.getObjId(path, type);
        switch (type) {
            //1指标 2任务 3项目报告
            case 1:
                targetMapper.updateFilePath(null, objId);
                break;
            case 2:
                taskMapper.updateFilePath(null, objId);
                break;
            case 3:
                itemMapper.updatePath(null, objId);
                break;
        }
    }

    public String getObjId(String path, Integer type) {
        String id = "";
        switch (type) {
            //1指标 2任务 3项目报告
            case 1:
                id = SuffixUtils.getId(path, 6);
                break;
            case 2:
                id = SuffixUtils.getId(path, 4);
                break;
            case 3:
                id = SuffixUtils.getId(path, 2);
                break;
        }
        return id;
    }

    public String formatViewUrl(String intactPath) {
        try {
            String ftpUrl = String.format("ftp://%s%s?ftp.username=%s&ftp.password=%s", hostname, intactPath, username, password);
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String urlEncode = base64Encoder.encode(ftpUrl.getBytes());
            String previewUrl = String.format("%surl=%s", kkFileViewPrefix, urlEncode);
            return previewUrl.replaceAll("\n", "").replaceAll("\r", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void ftpLogout(FTPClient ftpClient) {
        try {
            ftpClient.logout();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    public void exReport(String itemId) throws CustomException {

        ItemModel itemModel = itemMapper.findById(itemId);
        if (itemModel == null) throw new CustomException(5004, "无法找到此项目!");
        //创建word文档对象
        XWPFDocument document = new XWPFDocument();
        //创建标题
        XWPFParagraph title = document.createParagraph();
        //设置段落居中
        title.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleRun = title.createRun();
        titleRun.setColor("000000");
        titleRun.setFontSize(25);
        titleRun.setFontFamily("仿宋");
        titleRun.setBold(true);
        titleRun.setText(itemModel.getItemName() + "评估报告");
        titleRun.addBreak();//换行

        List<TaskModel> parentTask = taskMapper.findParentByItemId(itemModel.getItemId());

        for (TaskModel taskModel : parentTask) {
            //添加第一段落
            XWPFParagraph firstParagraph = document.createParagraph();
            //设置左对齐
            firstParagraph.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun firstRun = firstParagraph.createRun();
            firstRun.setColor("000000");
            firstRun.setFontSize(15);
            firstRun.setFontFamily("楷体");
            firstRun.setBold(true);
            firstRun.setText(taskModel.getTaskName());
            List<TaskModel> childTask = taskMapper.findByParentIt(taskModel.getTaskId());
            for (TaskModel taskModel1 : childTask) {
                //添加第一段落
                XWPFParagraph taskParagraph = document.createParagraph();
                //设置左对齐
                taskParagraph.setAlignment(ParagraphAlignment.LEFT);
                XWPFRun taskRun = taskParagraph.createRun();
                taskRun.setColor("000000");
                taskRun.setFontSize(10);
                taskRun.addTab();//缩进
                taskRun.setFontFamily("楷体");
                taskRun.setBold(true);
                taskRun.setText(taskModel1.getTaskName());
                List<TargetModel> byTaskId = targetMapper.findByTaskId(taskModel1.getTaskId());
                for (TargetModel targetModel : byTaskId) {
                    //添加第一段落
                    XWPFParagraph targetParagraph = document.createParagraph();
                    //设置左对齐
                    targetParagraph.setAlignment(ParagraphAlignment.LEFT);
                    XWPFRun targetRun = targetParagraph.createRun();
                    targetRun.setColor("000000");
                    targetRun.setFontSize(10);
                    targetRun.addTab();//缩进
                    targetRun.addTab();//缩进
                    targetRun.setFontFamily("楷体");
                    targetRun.setBold(true);
                    targetRun.setText("指标名称：");
                    targetRun.setText(targetModel.getTargetName());
                    targetRun.addBreak();//换行
                    targetRun.addTab();//缩进
                    targetRun.addTab();//缩进
                    targetRun.setText("结果：");
                    targetRun.setText(targetModel.getResult());
                    targetRun.addBreak();//换行
                    targetRun.addTab();//缩进
                    targetRun.addTab();//缩进
                    targetRun.setText("备注：");
                    targetRun.setText(targetModel.getRemark());
                    targetRun.addBreak();//换行
                    targetRun.addTab();//缩进
                    targetRun.addTab();//缩进
                    targetRun.setText("得分：");
                    targetRun.setText(String.valueOf(targetModel.getScore()));
                    targetRun.addBreak();//换行
                }
            }
        }
        ByteArrayOutputStream baos = null;
        ByteArrayInputStream in = null;
        try {
            baos = new ByteArrayOutputStream();//二进制OutputStream
            document.write(baos);//文档写入流
            in = new ByteArrayInputStream(baos.toByteArray());//OutputStream写入InputStream二进制流
            String path = this.getPath(itemId, 5);
            String pinyin = ZNUtils.toPinyin(Objects.requireNonNull(itemModel.getItemName()));
            this.uploadFile(path, pinyin + ".docx", in);
            List<ResourceModel> byObjIdAndPath = resourceService.findByObjIdAndPath(itemId, path + "/" + pinyin + ".docx");
            if (byObjIdAndPath.size() == 0) {
                ResourceModel resourceModel = new ResourceModel(itemId, itemModel.getItemName() + ".docx", path + "/" + pinyin + ".docx", 1);
                resourceService.addResource(resourceModel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
